package cn.com.cis.common.data;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.cis.domain.Privilege;
import cn.com.cis.service.PrivilegeService;

/**
 * 数据库基础数据初始化处理器
 */
public class BasicDatabaseDataInitialize {
	
	@Autowired
	private PrivilegeService privilegeService;

	@PostConstruct
	public void initialize() {
		try {
			rebuildPrivilageDataFromControllerAnnotation();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}

	private void rebuildPrivilageDataFromControllerAnnotation() throws ClassNotFoundException {
		ClassPathScanningCandidateComponentProvider scan = new ClassPathScanningCandidateComponentProvider(false);
		scan.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
		Set<BeanDefinition> beanDefinitions = scan.findCandidateComponents("");
		
        Set<String[]> mergedPermissions = new HashSet<String[]>();
        for (BeanDefinition beanDefinition : beanDefinitions) {
            String className = beanDefinition.getBeanClassName();
            
            Class<?> beanClass = Class.forName(className);
            
            // 获取注解在class头上的url,并去掉最后的斜杠
            RequestMapping classRm = beanClass.getAnnotation(RequestMapping.class);
            String classUrl = "";
            if(null != classRm){
            	classUrl = classRm.value()[0];
            	if(classUrl.endsWith("/")){
            		classUrl = classUrl.substring(0, classUrl.length() - 1);
            	}
            }
            
            
            Method[] methods = beanClass.getMethods();
            for (Method method : methods) {
                RequiresPermissions rp = (RequiresPermissions) method.getAnnotation(RequiresPermissions.class);
                
                // 获取注解在class头上的url
                String methodUrl = "";
                RequestMapping rm = (RequestMapping) method.getAnnotation(RequestMapping.class);
                if(null != rm){
                	methodUrl = rm.value()[0];
                	if(methodUrl.endsWith("}")){
                		// turn restful api url to static url, like: "/parameter/save/{jobId}" to "/parameter/save/num"
                		methodUrl = methodUrl.replaceAll("\\{.*\\}", "num");
                	}
                }
                
                String webUrl = classUrl + methodUrl;
                
                String code = "";
                
                if (rp != null) {
                    code = rp.value()[0];
                    mergedPermissions.add(new String[]{code, webUrl});
                }
                
            }
        }
        
        privilegeService.clearAll();
        
        int i = 0;
        for(String[] permissionCodeUrl : mergedPermissions){
        	Privilege privilege = new Privilege();
        	privilege.setId(i++);
        	privilege.setCode(permissionCodeUrl[0]);
        	privilege.setUrl(permissionCodeUrl[1]);
        	privilegeService.insertPrivilegeItem(privilege);
        }
	}
}
